import React, { useEffect, useState } from "react";
import {
  Layout,
  Card,
  Button,
  Tag,
  Statistic,
  Spin,
  Table,
  message,
} from "antd";
import ReactECharts from "echarts-for-react";
import axios from "../utils/request";
import { useNavigate, useLocation } from "react-router-dom";
import "./Dashboard.css";
import "./OperationOverview.css";
import {
  LinkOutlined,
  GithubOutlined,
  TeamOutlined,
  UserOutlined,
} from "@ant-design/icons";
import SidebarMenu from '../components/SidebarMenu';

const { Header, Content, Sider } = Layout;

const menuItems = [
  { label: "综合态势", path: "/dashboard" },
  { label: "运营管理", path: "/dashboard/enterprise" },
  { label: "物业管理", path: "/dashboard/property" },
  { label: "数据治理", path: "/dashboard/data" },
  { label: "能源管理", path: "/dashboard/energy" },
  { label: "园区卡口", path: "/dashboard/gate" },
];

// 统计卡片封装组件
function OverviewStats() {
  // 死数据，完全按图片内容
  const stats = [
    {
      icon: <LinkOutlined style={{ fontSize: 32, color: "#4B5EFF" }} />, // 蓝色
      title: "文章总数（篇）",
      value: 915,
      valueColor: "#4B5EFF",
      iconBg: "#ededed",
    },
    {
      icon: <GithubOutlined style={{ fontSize: 32, color: "#8B2BE2" }} />, // 紫色
      title: "潜在客户（个）",
      value: 536,
      valueColor: "#8B2BE2",
      iconBg: "#ededed",
    },
    {
      icon: <TeamOutlined style={{ fontSize: 32, color: "#FFA940" }} />, // 橙色
      title: "企业情况（家）",
      value: 694,
      valueColor: "#FFA940",
      iconBg: "#ededed",
    },
    {
      icon: <UserOutlined style={{ fontSize: 32, color: "#36B3FF" }} />, // 青蓝
      title: "园区用户（人）",
      value: 8536,
      valueColor: "#36B3FF",
      iconBg: "#ededed",
    },
  ];
  return (
    <div style={{ padding: "0 16px" }}>
      <div
        style={{
          display: "flex",
          gap: 48,
          marginBottom: 32,
          justifyContent: "center",
        }}
      >
        {stats.map((item, idx) => (
          <div
            key={idx}
            style={{ display: "flex", alignItems: "center", minWidth: 220 }}
          >
            <div
              style={{
                width: 56,
                height: 56,
                borderRadius: "50%",
                background: item.iconBg,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                marginRight: 16,
              }}
            >
              {item.icon}
            </div>
            <div>
              <div style={{ color: "#888", fontSize: 16, marginBottom: 2 }}>
                {item.title}
              </div>
              <div
                style={{
                  fontWeight: 700,
                  fontSize: 20,
                  color: item.valueColor,
                }}
              >
                {item.value}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// 待办事项死数据
const todoListStatic = [
  { title: "入驻待审核企业", count: 23, unit: "（家）" },
  { title: "合同签订待处理", count: 42, unit: "（单）" },
  { title: "租户物业费催缴", count: 22, unit: "（单）" },
  { title: "潜在客户待签单", count: 37, unit: "（单）" },
];

// 最新动态死数据
const newsListStatic = [
  {
    tag: "采集",
    tagColor: "#19c2a6",
    content: "我（超级管理员）通过了{公司的}入驻申请",
  },
  {
    tag: "采集",
    tagColor: "#19c2a6",
    content: "我（超级管理员）通过了{公司的}入驻申请",
  },
  {
    tag: "热门",
    tagColor: "#fa5252",
    content: "我（超级管理员）通过了{公司的}入驻申请",
  },
  {
    tag: "热门",
    tagColor: "#fa5252",
    content: "我（超级管理员）通过了{公司的}入驻申请",
  },
  {
    tag: "热门",
    tagColor: "#fa5252",
    content: "我（超级管理员）通过了{公司的}入驻申请",
  },
  {
    tag: "热门",
    tagColor: "#fab005",
    content: "我（超级管理员）通过了{公司的}入驻申请",
  },
];

// TOP10企业死数据
const top10Static = [
  { name: "杭州久策科技有限公司", talent: 287, value: 345 },
  { name: "杭州融智云科技有限公司", talent: 225, value: 298 },
  { name: "杭州智链科技有限公司", talent: 219, value: 289 },
  { name: "南宁可达靓成有限公司", talent: 203, value: 276 },
  { name: "杭州经纬科技有限公司", talent: 195, value: 269 },
  { name: "杭州经纬科技有限公司", talent: 182, value: 215 },
  { name: "砺砺（杭州）科技有限公司", talent: 170, value: 132 },
  { name: "杭州融智云科技有限公司", talent: 158, value: 56 },
  { name: "杭州精工智能科技有限公司", talent: 143, value: 52 },
  { name: "杭州精工智能科技有限公司", talent: 129, value: 32 },
];

// 企业资质死数据
const qualificationStatic = {
  stats: [
    { label: "上市公司", value: 88, color: "#19c2a6" },
    { label: "高新企业", value: 361, color: "#faad14" },
    { label: "规上企业", value: 682, color: "#1890ff" },
    { label: "专精特新企业", value: 682, color: "#1890ff" },
  ],
  bar: [
    { name: "能源", value: 200 },
    { name: "工业", value: 400 },
    { name: "农业", value: 800 },
    { name: "医疗", value: 1000 },
    { name: "新材料", value: 800 },
    { name: "交通", value: 400 },
    { name: "信息化服务业", value: 200 },
  ],
};

// 能源环形图死数据
const energyStatic = [
  { name: "煤", value: 40, color: "#36b3ff" },
  { name: "气", value: 21, color: "#4ecb73" },
  { name: "油品", value: 17, color: "#ffc542" },
  { name: "电", value: 13, color: "#ffd43b" },
  { name: "热", value: 9, color: "#fa5252" },
];
const energyTotal = 3245;

// 能源图标映射
const energyIcons = {
  '煤': (
    <svg width="18" height="18" viewBox="0 0 18 18" style={{verticalAlign:'middle'}}><circle cx="9" cy="9" r="7" fill="currentColor" /></svg>
  ),
  '气': (
    <svg width="18" height="18" viewBox="0 0 18 18" style={{verticalAlign:'middle'}}><ellipse cx="9" cy="9" rx="7" ry="5" fill="currentColor" /></svg>
  ),
  '油品': (
    <svg width="18" height="18" viewBox="0 0 18 18" style={{verticalAlign:'middle'}}><rect x="4" y="4" width="10" height="10" rx="3" fill="currentColor" /></svg>
  ),
  '电': (
    <svg width="18" height="18" viewBox="0 0 18 18" style={{verticalAlign:'middle'}}><polygon points="8,2 10,2 9,8 12,8 7,16 8.5,10 6,10" fill="currentColor" /></svg>
  ),
  '热': (
    <svg width="18" height="18" viewBox="0 0 18 18" style={{verticalAlign:'middle'}}><path d="M9 2 Q11 6 9 10 Q7 14 9 16" stroke="currentColor" strokeWidth="2" fill="none"/><circle cx="9" cy="14" r="2" fill="currentColor" /></svg>
  )
};

// 通用默认能源图标
const defaultEnergyIcon = (
  <svg width="18" height="18" viewBox="0 0 18 18" style={{verticalAlign:'middle'}}><circle cx="9" cy="9" r="7" fill="currentColor" /></svg>
);

const OperationOverview = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [summary, setSummary] = useState(null);
  const [todoList, setTodoList] = useState([]);
  const [newsList, setNewsList] = useState([]);
  const [top10, setTop10] = useState([]);
  const [qualification, setQualification] = useState([]);
  const [energy, setEnergy] = useState([]);
  const [loading, setLoading] = useState(true);
  const [group, setGroup] = useState("超级开发组");

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const [
          summaryRes,
          todoRes,
          newsRes,
          top10Res,
          qualificationRes,
          energyRes,
        ] = await Promise.all([
          axios.get("/api/operation/summary"),
          axios.get("/api/operation/todo"),
          axios.get("/api/operation/news"),
          axios.get("/api/operation/top10"),
          axios.get("/api/operation/qualification"),
          axios.get("/api/operation/energy"),
        ]);
        setSummary(summaryRes.data.data);
        setTodoList(todoRes.data.data);
        setNewsList(newsRes.data.data);
        setTop10(top10Res.data.data);
        setQualification(qualificationRes.data.data);
        setEnergy(energyRes.data.data);
      } catch (err) {
        // eslint-disable-next-line
        message.error("数据加载失败");
      }
      setLoading(false);
    };
    fetchData();
  }, []);

  const handleMenuClick = (item) => {
    navigate(item.path);
  };

  // Echarts option for Pie (园区双碳用能情况)
  const pieOption = {
    tooltip: { trigger: "item", formatter: "{b}: {c} ({d}%)" },
    legend: {
      orient: "vertical",
      right: 10,
      top: "center",
      textStyle: { color: "#22335b" },
    },
    series: [
      {
        name: "用能类型",
        type: "pie",
        radius: ["60%", "85%"],
        center: ["40%", "50%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: true,
          position: "outside",
          formatter: "{b}",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 18,
            fontWeight: "bold",
          },
        },
        labelLine: { show: true },
        data: energy.map((e) => ({ value: e.value, name: e.type })),
      },
    ],
  };

  if (loading) return <Spin size="large" style={{ marginTop: 100 }} />;

  return (
    <Layout className="dashboard-root">
      <Header className="dashboard-header">
        <div className="dashboard-header-left">
          <span className="dashboard-title">智慧园区管理平台</span>
          <span style={{ fontSize: 15, color: "#fff", marginLeft: 10 }}>
            项目地址：
          </span>
          <select
            value={group}
            className="dashboard-header-select"
            onChange={(e) => setGroup(e.target.value)}
          >
            <option value="超级开发组">超级开发组</option>
            <option value="测试组">测试组</option>
            <option value="运维组">运维组</option>
          </select>
        </div>
        <div className="dashboard-header-menu">
          {menuItems.map((item) => (
            <span
              key={item.path}
              className={
                "dashboard-header-menu-item" +
                (location.pathname === item.path
                  ? " dashboard-header-menu-item-active"
                  : "")
              }
              onClick={() => handleMenuClick(item)}
            >
              {item.label}
            </span>
          ))}
        </div>
        <div className="dashboard-header-right">
          <span className="dashboard-header-bell">
            <svg
              t="1712222222222"
              viewBox="0 0 1024 1024"
              width="20"
              height="20"
            >
              <path
                d="M512 960c-53.024 0-96-42.976-96-96h192c0 53.024-42.976 96-96 96z m352-192h-704c-17.664 0-32-14.336-32-32 0-17.664 14.336-32 32-32h32v-256c0-176.736 143.264-320 320-320s320 143.264 320 320v256h32c17.664 0 32 14.336 32 32 0 17.664-14.336 32-32 32z"
                fill="#fff"
              />
            </svg>
          </span>
          <span className="dashboard-header-user">momo.Lxw</span>
          <span className="dashboard-header-time">2025/7/2 10:24:33</span>
        </div>
      </Header>
      <Layout>
        <Sider width={220} className="dashboard-sider" style={{background:'#3b5b7e',minHeight:'100vh',boxShadow:'2px 0 8px rgba(0,0,0,0.08)'}}>
          <SidebarMenu onMenuClick={({ key }) => {
            if (key === 'content-1') {
              navigate('/article/publish');
            } else if (key === 'content-2') {
              navigate('/article/comment');
            } else if (key === 'business-1') {
              navigate('/business/contract');
            } else if (key === 'business-2') {
              navigate('/business/customer');
            } else if (key === 'tenant-1') {
              navigate('/tenant/info');
            } else if (key === 'tenant-2') {
              navigate('/tenant/staff');
            } else if (key === 'asset-1') {
              navigate('/building-manage'); // 新增：点击楼宇信息管理跳转
            } else if (key === 'asset-2') {
              navigate('/public-resource'); // 新增：点击公共资源管理跳转
            } else if (key === 'bill-1') {
              navigate('/car-bill'); // 新增：点击车辆收费账单跳转
            } else if (key === 'bill-2') {
              navigate('/tenant-bill'); // 新增：点击租户账单管理跳转
            }
          }} />
        </Sider>
        <Content
          className="dashboard-content"
          style={{ padding: 0, background: "#f5f7fa", minHeight: "100vh" }}
        >
          <div className="operation-overview">
            {/* 头部统计卡片 */}
            <OverviewStats />
            {/* 待办事项和最新动态 */}
            <div style={{ display: "flex", gap: 16, padding: "0 16px" }}>
              <div
                style={{
                  flex: 1,
                  background: "#fff",
                  borderRadius: 12,
                  boxShadow: "0 2px 8px rgba(0,0,0,0.03)",
                  padding: "24px 24px 18px 24px",
                  minWidth: 320,
                }}
              >
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    marginBottom: 18,
                  }}
                >
                  <div
                    style={{
                      width: 4,
                      height: 20,
                      background: "#3B5BDB",
                      borderRadius: 2,
                      marginRight: 8,
                    }}
                  ></div>
                  <span style={{ fontWeight: 700, fontSize: 17 }}>
                    待办事项
                  </span>
                </div>
                {todoListStatic.map((item, idx) => (
                  <div
                    key={idx}
                    style={{
                      display: "flex",
                      alignItems: "center",
                      marginBottom: idx === todoListStatic.length - 1 ? 0 : 14,
                    }}
                  >
                    <span style={{ flex: 1, color: "#222", fontSize: 15 }}>
                      {item.title}
                    </span>
                    <span
                      style={{
                        width: 38,
                        textAlign: "right",
                        color: "#3B5BDB",
                        fontWeight: 700,
                        fontSize: 15,
                      }}
                    >
                      {item.count}
                    </span>
                    <span
                      style={{
                        width: 28,
                        textAlign: "left",
                        color: "#888",
                        fontSize: 13,
                        marginLeft: 2,
                      }}
                    >
                      {item.unit}
                    </span>
                    <button
                      style={{
                        marginLeft: 18,
                        padding: "0 16px",
                        height: 28,
                        background: "#19c2a6",
                        border: "none",
                        borderRadius: 6,
                        color: "#fff",
                        fontWeight: 500,
                        fontSize: 14,
                        cursor: "pointer",
                        transition: "background 0.2s",
                        boxShadow: "0 1px 4px rgba(25,194,166,0.08)",
                      }}
                      onMouseOver={(e) =>
                        (e.currentTarget.style.background = "#13b197")
                      }
                      onMouseOut={(e) =>
                        (e.currentTarget.style.background = "#19c2a6")
                      }
                    >
                      我要处理
                    </button>
                  </div>
                ))}
              </div>
              <div
                style={{
                  flex: 1,
                  background: "#fff",
                  borderRadius: 12,
                  boxShadow: "0 2px 8px rgba(0,0,0,0.03)",
                  padding: "24px 24px 18px 24px",
                  minWidth: 320,
                }}
              >
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    marginBottom: 18,
                    justifyContent: "space-between",
                  }}
                >
                  <div style={{ display: "flex", alignItems: "center" }}>
                    <div
                      style={{
                        width: 4,
                        height: 20,
                        background: "#3B5BDB",
                        borderRadius: 2,
                        marginRight: 8,
                      }}
                    ></div>
                    <span style={{ fontWeight: 700, fontSize: 17 }}>
                      最新动态
                    </span>
                  </div>
                  <a
                    href="#"
                    style={{
                      color: "#3B5BDB",
                      fontSize: 14,
                      textDecoration: "none",
                      fontWeight: 500,
                    }}
                  >
                    more
                  </a>
                </div>
                {newsListStatic.map((item, idx) => (
                  <div
                    key={idx}
                    style={{
                      display: "flex",
                      alignItems: "center",
                      marginBottom: idx === newsListStatic.length - 1 ? 0 : 10,
                    }}
                  >
                    <span
                      style={{
                        display: "inline-block",
                        minWidth: 38,
                        padding: "0 10px",
                        height: 22,
                        lineHeight: "22px",
                        background: item.tagColor + "22",
                        color: item.tagColor,
                        borderRadius: 6,
                        fontSize: 13,
                        fontWeight: 500,
                        textAlign: "center",
                        marginRight: 12,
                        border: `1px solid ${item.tagColor}`,
                      }}
                    >
                      {item.tag}
                    </span>
                    <span style={{ color: "#555", fontSize: 15 }}>
                      {item.content}
                    </span>
                  </div>
                ))}
              </div>
            </div>
            {/* TOP10企业表格 */}
            <div
              style={{
                margin: "32px 16px 0 16px",
                background: "#fff",
                borderRadius: 12,
                boxShadow: "0 2px 8px rgba(0,0,0,0.03)",
                overflow: "hidden",
              }}
            >
              <div
                style={{
                  background: "#00d0e9",
                  color: "#fff",
                  fontWeight: 700,
                  fontSize: 18,
                  padding: "12px 0",
                  textAlign: "center",
                  letterSpacing: 1,
                }}
              >
                园区优质企业排名TOP10
              </div>
              <div style={{ padding: "0 0 18px 0" }}>
                <div
                  style={{
                    display: "flex",
                    background: "#fff",
                    fontWeight: 700,
                    fontSize: 15,
                    padding: "10px 0 8px 0",
                    borderBottom: "1px solid #f0f0f0",
                  }}
                >
                  <div style={{ flex: 2, paddingLeft: 32 }}>企业名称</div>
                  <div style={{ flex: 1, textAlign: "center" }}>高端人才数</div>
                  <div style={{ flex: 1, textAlign: "center" }}>
                    企业估值（亿元）
                  </div>
                </div>
                {top10Static.map((item, idx) => (
                  <div
                    key={idx}
                    style={{
                      display: "flex",
                      background: idx % 2 === 0 ? "#f8fafd" : "#fff",
                      fontSize: 15,
                      padding: "10px 0 8px 0",
                      alignItems: "center",
                    }}
                  >
                    <div style={{ flex: 2, paddingLeft: 32, color: "#222" }}>
                      {item.name}
                    </div>
                    <div
                      style={{
                        flex: 1,
                        textAlign: "center",
                        color: "#00b2e9",
                        fontWeight: 600,
                      }}
                    >
                      {item.talent}
                    </div>
                    <div
                      style={{
                        flex: 1,
                        textAlign: "center",
                        color: "#00b2e9",
                        fontWeight: 600,
                      }}
                    >
                      {item.value}
                    </div>
                  </div>
                ))}
              </div>
            </div>
            <div
              style={{
                display: "flex",
                gap: 16,
                margin: "16px 0",
                padding: "0 16px",
              }}
            >
              {/* 企业资质情况 柱状图+统计 */}
              <div
                style={{
                  flex: 1,
                  background: "#fff",
                  borderRadius: 12,
                  boxShadow: "0 2px 8px rgba(0,0,0,0.03)",
                  padding: "24px 24px 18px 24px",
                  marginRight: 16,
                }}
              >
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    marginBottom: 18,
                  }}
                >
                  <div
                    style={{
                      width: 4,
                      height: 20,
                      background: "#3B5BDB",
                      borderRadius: 2,
                      marginRight: 8,
                    }}
                  ></div>
                  <span style={{ fontWeight: 700, fontSize: 17 }}>
                    园区企业资质情况
                  </span>
                </div>
                <div
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    marginBottom: 18,
                  }}
                >
                  {qualificationStatic.stats.map((item, idx) => (
                    <div key={idx} style={{ textAlign: "center", flex: 1 }}>
                      <div
                        style={{ color: "#888", fontSize: 15, marginBottom: 2 }}
                      >
                        {item.label}
                      </div>
                      <div
                        style={{
                          fontWeight: 700,
                          fontSize: 22,
                          color: item.color,
                          marginBottom: 2,
                        }}
                      >
                        {item.value}
                      </div>
                    </div>
                  ))}
                </div>
                {/* 柱状图，带悬浮提示 */}
                <BarChartWithTooltip data={qualificationStatic.bar} />
              </div>
              {/* 园区双碳用能情况 环形图 */}
              <div
                style={{
                  flex: 1,
                  background: "#fff",
                  borderRadius: 12,
                  boxShadow: "0 2px 8px rgba(0,0,0,0.03)",
                  padding: "24px 24px 18px 24px",
                  minWidth: 420,
                }}
              >
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    marginBottom: 18,
                    justifyContent: "space-between",
                  }}
                >
                  <div style={{ display: "flex", alignItems: "center" }}>
                    <div
                      style={{
                        width: 4,
                        height: 20,
                        background: "#3B5BDB",
                        borderRadius: 2,
                        marginRight: 8,
                      }}
                    ></div>
                    <span style={{ fontWeight: 700, fontSize: 17 }}>
                      园区双碳用能情况
                    </span>
                  </div>
                  <div>
                    <button
                      style={{
                        marginRight: 8,
                        padding: "2px 16px",
                        background: "#e6f7ff",
                        color: "#36b3ff",
                        border: "none",
                        borderRadius: 6,
                        fontWeight: 500,
                        fontSize: 14,
                        cursor: "pointer",
                      }}
                    >
                      能耗情况
                    </button>
                    <button
                      style={{
                        padding: "2px 16px",
                        background: "#fff7e6",
                        color: "#faad14",
                        border: "none",
                        borderRadius: 6,
                        fontWeight: 500,
                        fontSize: 14,
                        cursor: "pointer",
                      }}
                    >
                      碳排情况
                    </button>
                  </div>
                </div>
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                  }}
                >
                  <EnergyDonutChart data={energyStatic} total={energyTotal} />
                  <div style={{ marginLeft: 32 }}>
                    {energyStatic.map((item, idx) => (
                      <div
                        key={item.name}
                        style={{
                          display: "flex",
                          alignItems: "center",
                          marginBottom: 10,
                        }}
                      >
                        <span
                          style={{
                            display: "inline-block",
                            width: 14,
                            height: 14,
                            borderRadius: "50%",
                            background: item.color,
                            marginRight: 8,
                          }}
                        ></span>
                        <span style={{ color: "#555", fontSize: 15 }}>
                          {item.name}
                        </span>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </Content>
      </Layout>
    </Layout>
  );
};

// 柱状图带tooltip组件
function BarChartWithTooltip({ data }) {
  const [hoverIdx, setHoverIdx] = useState(null);
  const [mousePos, setMousePos] = useState({ x: 0, y: 0 });
  const barWidth = 48;
  const gap = 36;
  return (
    <div style={{ width: "100%", height: 260, position: "relative" }}>
      <svg
        width="100%"
        height="100%"
        viewBox="0 0 700 260"
        style={{ display: "block" }}
      >
        {/* y轴刻度线和标签 */}
        {[0, 200, 400, 600, 800, 1000].map((y, i) => (
          <g key={y}>
            <line
              x1="60"
              y1={240 - y * 0.2}
              x2="680"
              y2={240 - y * 0.2}
              stroke="#eee"
              strokeWidth="1"
            />
            <text x="30" y={245 - y * 0.2} fontSize="12" fill="#888">
              {y}
            </text>
          </g>
        ))}
        {/* x轴标签和柱子 */}
        {data.map((item, idx) => {
          const x = 60 + idx * (barWidth + gap);
          const barHeight = item.value * 0.2;
          return (
            <g key={item.name}>
              <rect
                x={x}
                y={240 - barHeight}
                width={barWidth}
                height={barHeight}
                rx="8"
                fill="url(#barGradient)"
                style={{ cursor: "pointer" }}
                onMouseEnter={(e) => {
                  setHoverIdx(idx);
                  const svgRect =
                    e.target.ownerSVGElement.getBoundingClientRect();
                  setMousePos({
                    x: e.clientX - svgRect.left,
                    y: e.clientY - svgRect.top,
                  });
                }}
                onMouseLeave={() => setHoverIdx(null)}
              />
              <text
                x={x + barWidth / 2}
                y={258}
                fontSize="13"
                fill="#888"
                textAnchor="middle"
              >
                {item.name}
              </text>
              <text
                x={x + barWidth / 2}
                y={240 - barHeight - 8}
                fontSize="14"
                fill="#1890ff"
                textAnchor="middle"
                fontWeight="700"
              >
                {item.value}
              </text>
            </g>
          );
        })}
        {/* 渐变定义 */}
        <defs>
          <linearGradient id="barGradient" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#36b3ff" />
            <stop offset="100%" stopColor="#1890ff" />
          </linearGradient>
        </defs>
      </svg>
      <span
        style={{
          position: "absolute",
          left: 0,
          top: 0,
          fontSize: 13,
          color: "#888",
        }}
      >
        单位/家
      </span>
      {hoverIdx !== null && (
        <div
          style={{
            position: "absolute",
            left: mousePos.x + 10,
            top: mousePos.y - 40,
            background: "#fff",
            color: "#222",
            border: "1px solid #e6e6e6",
            borderRadius: 6,
            boxShadow: "0 2px 8px rgba(0,0,0,0.08)",
            padding: "8px 16px",
            fontSize: 14,
            pointerEvents: "none",
            zIndex: 10,
          }}
        >
          <div>
            <b>{data[hoverIdx].name}</b>
          </div>
          <div>数量：{data[hoverIdx].value}</div>
        </div>
      )}
    </div>
  );
}

// 环形图组件，支持点击高亮和显示数据
function EnergyDonutChart({ data, total }) {
  // 默认高亮"热"扇区（最后一个）
  const [activeIdx, setActiveIdx] = useState(data.length - 1);
  // 计算每个扇区的起止角度
  let sum = data.reduce((a, b) => a + b.value, 0);
  let angles = [];
  let acc = 0;
  for (let i = 0; i < data.length; i++) {
    let start = acc;
    let end = acc + (data[i].value / sum) * 360;
    angles.push([start, end]);
    acc = end;
  }
  // 极坐标转xy
  function polarToXY(cx, cy, r, angle) {
    let rad = ((angle - 90) * Math.PI) / 180;
    return [cx + r * Math.cos(rad), cy + r * Math.sin(rad)];
  }
  // 生成path
  function describeArc(cx, cy, r, innerR, startAngle, endAngle) {
    let [sx, sy] = polarToXY(cx, cy, r, endAngle);
    let [ex, ey] = polarToXY(cx, cy, r, startAngle);
    let [isx, isy] = polarToXY(cx, cy, innerR, endAngle);
    let [iex, iey] = polarToXY(cx, cy, innerR, startAngle);
    let largeArc = endAngle - startAngle > 180 ? 1 : 0;
    return `M${isx},${isy} L${sx},${sy} A${r},${r} 0 ${largeArc} 0 ${ex},${ey} L${iex},${iey} A${innerR},${innerR} 0 ${largeArc} 1 ${isx},${isy} Z`;
  }
  // 计算百分比
  function getPercent(val) {
    return Math.round((val / sum) * 100);
  }
  // 标签半径
  const labelRadius = 210;
  // 引导线半径
  const lineRadius = 150;
  // 标签避让：上下错位
  const labelOffsets = [-18, 0, 18, -10, 10];
  return (
    <div style={{ position: "relative", width: 320, height: 320 }}>
      <svg width={320} height={320} style={{ display: "block" }}>
        {data.map((item, idx) => {
          const midAngle = (angles[idx][0] + angles[idx][1]) / 2;
          const [lx, ly] = polarToXY(160, 160, labelRadius, midAngle);
          const [lineEndX, lineEndY] = polarToXY(160, 160, 150, midAngle);
          // 标签左右对齐
          const align = midAngle > 270 || midAngle < 90 ? "start" : "end";
          const textX = align === "start" ? lx + 8 : lx - 8;
          // 避让：上下错位
          const offsetY = labelOffsets[idx % labelOffsets.length];
          return (
            <g key={item.name}>
              {/* 引导线：虚线+圆点 */}
              <polyline
                points={
                  align === "start"
                    ? `${lineEndX},${lineEndY} ${lx - 10},${ly + offsetY} ${lx + 24},${ly + offsetY}`
                    : `${lineEndX},${lineEndY} ${lx + 10},${ly + offsetY} ${lx - 24},${ly + offsetY}`
                }
                fill="none"
                stroke={item.color}
                strokeWidth={2}
                strokeDasharray="3,2"
              />
              <circle cx={lineEndX} cy={lineEndY} r={4} fill={item.color} />
              {/* 图标+文字标签 */}
              <foreignObject x={align === "start" ? textX : textX - 60} y={ly + offsetY - 12} width="120" height="24">
                <div style={{display:'flex',alignItems:'center',color:item.color,fontWeight:700,fontSize:16,background:'none',userSelect:'none',pointerEvents:'none'}}>
                  <span style={{marginRight:4,display:'flex',alignItems:'center'}}>{energyIcons[item.name.trim()] || defaultEnergyIcon}</span>
                  <span>{item.name}:{getPercent(item.value)}%</span>
                </div>
              </foreignObject>
            </g>
          );
        })}
        {/* 环形本体 */}
        {data.map((item,idx) => (
          <path
            key={item.name}
            d={describeArc(160,160,140,100,angles[idx][0],angles[idx][1])}
            fill={item.color}
            fillOpacity={activeIdx === idx ? 1 : 0.7}
            style={{ cursor: "pointer", filter: activeIdx === idx ? "drop-shadow(0 2px 8px rgba(0,0,0,0.10))" : "none" }}
            onClick={() => setActiveIdx(idx)}
          />
        ))}
      </svg>
      {/* 中心总量 */}
      <div
        style={{
          position: "absolute",
          left: 0,
          top: 0,
          width: 320,
          height: 320,
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
          pointerEvents: "none",
        }}
      >
        <div style={{ color: "#888", fontSize: 15, marginBottom: 2 }}>
          能耗总量
        </div>
        <div
          style={{
            fontWeight: 700,
            fontSize: 32,
            color: "#222",
            marginBottom: 2,
          }}
        >
          {total}
        </div>
        <div style={{ color: "#888", fontSize: 14 }}>吨标煤</div>
        {activeIdx !== null && (
          <div
            style={{
              marginTop: 10,
              padding: "6px 18px",
              background: "#fff",
              border: "1px solid #e6e6e6",
              borderRadius: 8,
              boxShadow: "0 2px 8px rgba(0,0,0,0.08)",
              color: "#222",
              fontSize: 15,
            }}
          >
            <b>{data[activeIdx].name}</b>：{data[activeIdx].value}（{getPercent(data[activeIdx].value)}%）
          </div>
        )}
      </div>
    </div>
  );
}

export default OperationOverview;
